﻿NSMobile.models.Contact = Ext.regModel('Contact', {
    fields: [
        'firstName',
        'lastName',
        'thumb',
        'birthdate',
        'category',
        'commpref',
        'homephone',
        'mobilephone',
        'workphone',
        'email',
        'address',
        'gender',
        'rsvp',
        'customer',
        { name: 'onlinetotal', type: 'float' },
        { name: 'generation', type: 'int' },
        'level',
        { name: 'prv', type: 'float' },
        { name: 'twv', type: 'float' },
        { name: 'gwv', type: 'float' },
        { name: 'accountnumber', type: 'int' },
        { name: 'accountid', type: 'int' },
        { name: 'sortorder', type: 'int' },
        { name: 'lastpurchasedate', type: 'date' }
    ],
    getGroupString: function () {
        //return ((this.get('lastName').replace(/[()?]/g, '') || this.get('firstName').replace(/[()?]/g, ''))[0] || '').toUpperCase();
        return ((this.get('lastName') || this.get('firstName'))[0] || '').toUpperCase();
    }
});

//NSMobile.stores.teamContacts = new Ext.data.JsonStore({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'ajax',
//        url: serviceURI + '/GetTeam',
//        listeners: {
//            exception: {
//                fn: function (proxy, response, operation) {
//                    showErrorOnce();
//                }
//            }
//        },
//        timeout: ajaxTimeout
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    },
//    listeners: {
//        beforeload: {
//            fn: function () {
//                setSyncIcon('user_list', true);
//            }
//        },
//        load: {
//            fn: function () {
//                //var storageData = getStorage('teamContacts');
//                //storageData.contacts = storageData.contacts || {};
//                //var contacts = {};
////                for (var i = 0; i < NSMobile.stores.teamContacts.data.length; i++) {
////                    var contact = NSMobile.stores.teamContacts.getAt(i);
////                    contacts[contact.data.accountnumber] = contact.data;
////                }
////                Ext.apply(storageData.contacts, contacts);
////                setStorage('teamContacts', storageData);
//                teamLoaded = true;
//                //NSMobile.stores.local.teamContacts.load();

//                if (!NSMobile.stores.groupContacts.isLoading() && !NSMobile.stores.aflContacts.isLoading() && !NSMobile.stores.customerContacts.isLoading())
//                    setSyncIcon('user_list', false);
//            }
//        }
//    }
//});

NSMobile.stores.teamContactsPaginated = new Ext.data.JsonStore({
    model: 'Contact',
    sorters: 'lastName',
    pageSize: pageSize,
    remoteSort: true,
    remoteFilter: true,
    proxy: {
        headers: { "Content-Type": "application/json" },
        type: 'ajax',
        url: serviceURI + '/GetTeamPaginated',
        startParam: 'start',
        limitParam: 'count',
        listeners: {
            exception: {
                fn: function (proxy, response, operation) {
                    showErrorOnce();
                }
            }
        },
        timeout: ajaxTimeout
    },
    getGroupString: function (record) {
        return record.getGroupString();
    },
    listeners: {
        beforeload: {
            fn: function () {
                setSyncIcon('user_list', true);
            }
        },
        load: {
            fn: function () {
                if (NSMobile.stores.teamContactsPaginated.data.length == 0 && NSMobile.stores.teamContactsPaginated.currentPage > 1)
                    NSMobile.stores.teamContactsPaginated.previousPage();
                //var storageData = getStorage('teamContacts');
                //storageData.contacts = storageData.contacts || {};
                //var contacts = {};
                //                for (var i = 0; i < NSMobile.stores.teamContacts.data.length; i++) {
                //                    var contact = NSMobile.stores.teamContacts.getAt(i);
                //                    contacts[contact.data.accountnumber] = contact.data;
                //                }
                //                Ext.apply(storageData.contacts, contacts);
                //                setStorage('teamContacts', storageData);
                teamLoaded = true;
                //NSMobile.stores.local.teamContacts.load();

                if (!NSMobile.stores.groupContactsPaginated.isLoading() && !NSMobile.stores.aflContacts.isLoading() && !NSMobile.stores.customerContactsPaginated.isLoading())
                    setSyncIcon('user_list', false);
            }
        }
    }
});

//NSMobile.stores.local.teamContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'memory',
//        reader: {
//            type: 'json'
//        },
//        read: function (operation, callback, scope) {
//            var storageData = getStorage('teamContacts');
//            var contacts = [];

//            for (var key in storageData.contacts)
//                contacts.push(new this.model(storageData.contacts[key]));

//            if (!teamLoaded)
//                NSMobile.stores.teamContacts.load();

//            operation.resultSet = new Ext.data.ResultSet({
//                records: contacts,
//                total: contacts.length,
//                loaded: true
//            });
//            operation.setSuccessful();
//            operation.setCompleted();

//            if (typeof callback == 'function') {
//                callback.call(scope || this, operation);
//            }
//        }
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    }
//});

//NSMobile.stores.groupContacts = new Ext.data.JsonStore({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'ajax',
//        url: serviceURI + '/GetGroup',
//        listeners: {
//            exception: {
//                fn: function (proxy, response, operation) {
//                    showErrorOnce();
//                }
//            }
//        },
//        timeout: ajaxTimeout
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    },
//    listeners: {
//        beforeload: {
//            fn: function () {
//                setSyncIcon('user_list', true);
//            }
//        },
//        load: {
//            fn: function () {
////                var storageData = getStorage('groupContacts');
////                storageData.contacts = storageData.contacts || {};
////                var contacts = {};
////                for (var i = 0; i < NSMobile.stores.groupContacts.data.length; i++) {
////                    var contact = NSMobile.stores.groupContacts.getAt(i);
////                    contacts[contact.data.accountnumber] = contact.data;
////                }
////                Ext.apply(storageData.contacts, contacts);
////                setStorage('groupContacts', storageData);
//                groupLoaded = true;
//                //NSMobile.stores.local.groupContacts.load();

//                if (!NSMobile.stores.teamContactsPaginated.isLoading() && !NSMobile.stores.aflContacts.isLoading() && !NSMobile.stores.customerContacts.isLoading())
//                    setSyncIcon('user_list', false);
//            }
//        }
//    }
//});

NSMobile.stores.groupContactsPaginated = new Ext.data.JsonStore({
    model: 'Contact',
    sorters: 'lastName',
    pageSize: pageSize,
    remoteSort: true,
    remoteFilter: true,
    proxy: {
        type: 'ajax',
        url: serviceURI + '/GetGroupPaginated',
        startParam: 'start',
        limitParam: 'count',
        listeners: {
            exception: {
                fn: function (proxy, response, operation) {
                    showErrorOnce();
                }
            }
        },
        timeout: ajaxTimeout
    },
    getGroupString: function (record) {
        return record.getGroupString();
    },
    listeners: {
        beforeload: {
            fn: function () {
                setSyncIcon('user_list', true);
            }
        },
        load: {
            fn: function () {
                if (NSMobile.stores.groupContactsPaginated.data.length == 0 && NSMobile.stores.groupContactsPaginated.currentPage > 1)
                    NSMobile.stores.groupContactsPaginated.previousPage();
                //                var storageData = getStorage('groupContacts');
                //                storageData.contacts = storageData.contacts || {};
                //                var contacts = {};
                //                for (var i = 0; i < NSMobile.stores.groupContacts.data.length; i++) {
                //                    var contact = NSMobile.stores.groupContacts.getAt(i);
                //                    contacts[contact.data.accountnumber] = contact.data;
                //                }
                //                Ext.apply(storageData.contacts, contacts);
                //                setStorage('groupContacts', storageData);
                groupLoaded = true;
                //NSMobile.stores.local.groupContacts.load();

                if (!NSMobile.stores.teamContactsPaginated.isLoading() && !NSMobile.stores.aflContacts.isLoading() && !NSMobile.stores.customerContactsPaginated.isLoading())
                    setSyncIcon('user_list', false);
            }
        }
    }
});

//NSMobile.stores.local.groupContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'memory',
//        reader: {
//            type: 'json'
//        },
//        read: function (operation, callback, scope) {
//            var storageData = getStorage('groupContacts');
//            var contacts = [];

//            for (var key in storageData.contacts)
//                contacts.push(new this.model(storageData.contacts[key]));

//            if (!groupLoaded)
//                NSMobile.stores.groupContacts.load();

//            operation.resultSet = new Ext.data.ResultSet({
//                records: contacts,
//                total: contacts.length,
//                loaded: true
//            });
//            operation.setSuccessful();
//            operation.setCompleted();

//            if (typeof callback == 'function') {
//                callback.call(scope || this, operation);
//            }
//        }
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    }
//});

NSMobile.stores.aflContacts = new Ext.data.JsonStore({
    model: 'Contact',
    sorters: 'lastName',
    proxy: {
        type: 'ajax',
        url: serviceURI + '/GetAFL',
        listeners: {
            exception: {
                fn: function (proxy, response, operation) {
                    showErrorOnce();
                }
            }
        },
        timeout: ajaxTimeout
    },
    getGroupString: function (record) {
        return record.getGroupString();
    },
    listeners: {
        beforeload: {
            fn: function () {
                setSyncIcon('user_list', true);
            }
        },
        load: {
            fn: function () {
//                var storageData = getStorage('aflContacts');
//                storageData.contacts = storageData.contacts || {};
//                var contacts = {};
//                for (var i = 0; i < NSMobile.stores.aflContacts.data.length; i++) {
//                    var contact = NSMobile.stores.aflContacts.getAt(i);
//                    contacts[contact.data.accountnumber] = contact.data;
//                }
//                Ext.apply(storageData.contacts, contacts);
//                setStorage('aflContacts', storageData);
                aflLoaded = true;
                //NSMobile.stores.local.aflContacts.load();

                if (!NSMobile.stores.groupContactsPaginated.isLoading() && !NSMobile.stores.teamContactsPaginated.isLoading() && !NSMobile.stores.customerContactsPaginated.isLoading())
                    setSyncIcon('user_list', false);
            }
        }
    }
});

//NSMobile.stores.local.aflContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'memory',
//        reader: {
//            type: 'json'
//        },
//        read: function (operation, callback, scope) {
//            var storageData = getStorage('aflContacts');
//            var contacts = [];

//            for (var key in storageData.contacts)
//                contacts.push(new this.model(storageData.contacts[key]));

//            if (!aflLoaded)
//                NSMobile.stores.aflContacts.load();

//            operation.resultSet = new Ext.data.ResultSet({
//                records: contacts,
//                total: contacts.length,
//                loaded: true
//            });
//            operation.setSuccessful();
//            operation.setCompleted();

//            if (typeof callback == 'function') {
//                callback.call(scope || this, operation);
//            }
//        }
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    }
//});

NSMobile.stores.perfContacts = new Ext.data.Store({ //for performance lists
    model: 'Contact',
    sorters: 'lastName',
    remoteSort: true,
    proxy: {
        type: 'memory',
        reader: {
            type: 'json'
        },
        read: function (operation, callback, scope) {
            var me = this;
            perfContactStore.clearFilter();
            perfContactStore.sorters.clear();
            perfContactStore.sorters.add({ property: 'sortorder', direction: 'asc' });
            perfContactStore.currentPage = operation.page;
            perfContactStore.read({
                page: operation.page,
                start: operation.start,
                limit: operation.limit,
                callback: function (records, callbackOperation, success) {
                    operation.resultSet = new Ext.data.ResultSet({
                        records: records,
                        total: records.length,
                        loaded: true
                    });
                    operation.setSuccessful();
                    operation.setCompleted();

                    if (typeof callback == 'function')
                        callback.call(scope || me, operation);
                }
            });
            networkSorted = true;
        }
    }
});

//NSMobile.stores.customerContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'ajax',
//        url: serviceURI + '/GetCustomers',
//        listeners: {
//            exception: {
//                fn: function (proxy, response, operation) {
//                    showErrorOnce();
//                }
//            }
//        },
//        timeout: ajaxTimeout
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    },
//    listeners: {
//        beforeload: {
//            fn: function () {
//                setSyncIcon('user_list', true);
//            }
//        },
//        load: {
//            fn: function () {
////                var storageData = getStorage('customerContacts');
////                storageData.contacts = storageData.contacts || {};
////                var contacts = {};
////                for (var i = 0; i < NSMobile.stores.customerContacts.data.length; i++) {
////                    var contact = NSMobile.stores.customerContacts.getAt(i);
////                    contacts[contact.data.accountid] = contact.data;
////                }
////                Ext.apply(storageData.contacts, contacts);
////                setStorage('customerContacts', storageData);
//                customersLoaded = true;
//                //NSMobile.stores.local.customerContacts.load();

//                if (!NSMobile.stores.groupContactsPaginated.isLoading() && !NSMobile.stores.teamContactsPaginated.isLoading() && !NSMobile.stores.aflContacts.isLoading())
//                    setSyncIcon('user_list', false);
//            }
//        }
//    }
//});

NSMobile.stores.customerContactsPaginated = new Ext.data.Store({
    model: 'Contact',
    sorters: 'lastName',
    pageSize: pageSize,
    remoteSort: true,
    remoteFilter: true,
    proxy: {
        type: 'ajax',
        url: serviceURI + '/GetCustomersPaginated',
        startParam: 'start',
        limitParam: 'count',
        listeners: {
            exception: {
                fn: function (proxy, response, operation) {
                    showErrorOnce();
                }
            }
        },
        timeout: ajaxTimeout
    },
    getGroupString: function (record) {
        return record.getGroupString();
    },
    listeners: {
        beforeload: {
            fn: function () {
                setSyncIcon('user_list', true);
            }
        },
        load: {
            fn: function () {
                if (NSMobile.stores.customerContactsPaginated.data.length == 0 && NSMobile.stores.customerContactsPaginated.currentPage > 1)
                    NSMobile.stores.customerContactsPaginated.previousPage();
                //                var storageData = getStorage('customerContacts');
                //                storageData.contacts = storageData.contacts || {};
                //                var contacts = {};
                //                for (var i = 0; i < NSMobile.stores.customerContacts.data.length; i++) {
                //                    var contact = NSMobile.stores.customerContacts.getAt(i);
                //                    contacts[contact.data.accountid] = contact.data;
                //                }
                //                Ext.apply(storageData.contacts, contacts);
                //                setStorage('customerContacts', storageData);
                customersLoaded = true;
                //NSMobile.stores.local.customerContacts.load();

                if (!NSMobile.stores.groupContactsPaginated.isLoading() && !NSMobile.stores.teamContactsPaginated.isLoading() && !NSMobile.stores.aflContacts.isLoading())
                    setSyncIcon('user_list', false);
            }
        }
    }
});

//NSMobile.stores.local.customerContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'memory',
//        reader: {
//            type: 'json'
//        },
//        read: function (operation, callback, scope) {
//            var storageData = getStorage('customerContacts');
//            var contacts = [];

//            for (var key in storageData.contacts)
//                contacts.push(new this.model(storageData.contacts[key]));

//            if (!customersLoaded)
//                NSMobile.stores.customerContacts.load();

//            operation.resultSet = new Ext.data.ResultSet({
//                records: contacts,
//                total: contacts.length,
//                loaded: true
//            });
//            operation.setSuccessful();
//            operation.setCompleted();

//            if (typeof callback == 'function') {
//                callback.call(scope || this, operation);
//            }
//        }
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    }
//    //sorters: [ //customer list doesnt sort grouped contacts properly for some reason. this fixes that
//    //    {
//    //        direction: 'ASC',
//    //        sorterFn: function (obj1, obj2) {
//    //            //var n1 = ((obj1.data.lastName || obj1.data.firstName) || '')[0];
//    //            //var n2 = ((obj2.data.lastName || obj2.data.firstName) || '')[0];
//    //            //return n1 > n2 ? 1 : (n1 < n2 ? -1 : 0);
//    //
//    //            var cnt = 0, ax, tem;
//    //            var a = ((obj1.data.lastName || obj1.data.firstName) || '').toLowerCase();
//    //            var b = ((obj2.data.lastName || obj2.data.firstName) || '').toLowerCase();
//    //            if (a == b) return 0;
//    //            var x = /^(\.)?\d/;
//    //
//    //            var L = Math.min(a.length, b.length) + 1;
//    //            while (cnt < L && a.charAt(cnt) === b.charAt(cnt) &&
//    //        x.test(b.substring(cnt)) == false && x.test(a.substring(cnt)) == false) cnt++;
//    //            a = a.substring(cnt);
//    //            b = b.substring(cnt);
//    //
//    //            if (x.test(a) || x.test(b)) {
//    //                if (x.test(a) == false) return (a) ? 1 : -1;
//    //                else if (x.test(b) == false) return (b) ? -1 : 1;
//    //                else {
//    //                    tem = parseFloat(a) - parseFloat(b);
//    //                    if (tem != 0) return tem;
//    //                    else tem = a.search(/[^\.\d]/);
//    //                    if (tem == -1) tem = b.search(/[^\.\d]/);
//    //                    a = a.substring(tem);
//    //                    b = b.substring(tem);
//    //                }
//    //            }
//    //            if (a == b) return 0;
//    //            else return (a > b) ? 1 : -1;
//    //        }
//    //    }
//    //]
//});

NSMobile.stores.prospectContacts = new Ext.data.JsonStore({
    model: 'Contact',
    sorters: 'lastName',
    proxy: {
        type: 'ajax',
        url: serviceURI + '/GetProspects',
        listeners: {
            exception: {
                fn: function (proxy, response, operation) {
                    showErrorOnce();
                }
            }
        },
        timeout: ajaxTimeout
    },
    getGroupString: function (record) {
        return record.getGroupString();
    },
    listeners: {
        load: {
            fn: function () {
                prospectsLoaded = true;
            }
        }
    }
});

//NSMobile.stores.local.prospectContacts = new Ext.data.Store({
//    model: 'Contact',
//    sorters: 'lastName',
//    proxy: {
//        type: 'memory',
//        reader: {
//            type: 'json'
//        },
//        read: function (operation, callback, scope) {
//            var storageData = getStorage('prospectContacts');
//            var contacts = [];

//            for (var key in storageData.contacts)
//                contacts.push(new this.model(storageData.contacts[key]));

//            if (!prospectsLoaded)
//                NSMobile.stores.aflContacts.load();

//            operation.resultSet = new Ext.data.ResultSet({
//                records: contacts,
//                total: contacts.length,
//                loaded: true
//            });
//            operation.setSuccessful();
//            operation.setCompleted();

//            if (typeof callback == 'function') {
//                callback.call(scope || this, operation);
//            }
//        }
//    },
//    getGroupString: function (record) {
//        return record.getGroupString();
//    }
//});

NSMobile.stores.partyGuests = new Ext.data.Store({ //stub for guestlist as lists require stores
    model: 'Contact',
    sorters: 'lastName',
    proxy: {
        type: 'memory',
        reader: {
            type: 'json'
        }
    }
});

NSMobile.stores.allContacts = new Ext.data.Store({
    model: 'Contact',
    sorters: 'lastName',
    getGroupString: function (record) {
        return record.getGroupString();
    },
    proxy: {
        type: 'memory',
        reader: {
            type: 'json'
        }
    }
});

NSMobile.stores.phoneContacts = new Ext.data.Store({
    model: 'Contact',
    sorters: 'lastName',
    getGroupString: function (record) {
        return record.getGroupString();
    },
    proxy: {
        type: 'memory',
        reader: {
            type: 'json'
        }
    }
});

function loadPhoneContacts() {
    if (navigator.service)
        navigator.service.contacts.find(['name', 'emails'], function (phoneContacts) {
            var contacts = [];
            for (var i = 0; i < phoneContacts.length; i++) {
                var phoneContact = phoneContacts[i];
                var contact = new NSMobile.models.Contact();
                contact.data.firstName = phoneContact.name.givenName;
                contact.data.lastName = phoneContact.name.familyName;
                contact.data.email = phoneContact.emails[0].value;
                contacts.push(contact);
            }
            NSMobile.stores.phoneContacts.loadData(contacts, false);
        });
}

function loadAllContacts() {
    if (contactsLoaded || lock)
        return;

    lock = true;

    if (!teamLoaded)
        NSMobile.stores.teamContactsPaginated.load(function () { loadAllContacts(); });
    if (!customersLoaded)
        NSMobile.stores.customerContactsPaginated.load(function () { loadAllContacts(); });
    if (!groupLoaded)
        NSMobile.stores.groupContactsPaginated.load(function () { loadAllContacts(); });
    if (!aflLoaded)
        NSMobile.stores.aflContacts.load(function () { loadAllContacts(); });

    if (teamLoaded && customersLoaded && groupLoaded && aflLoaded) {
        var contacts = [];
        NSMobile.stores.teamContacts.each(function (item) { contacts.push(item.data); });
        NSMobile.stores.customerContactsPaginated.each(function (item) { contacts.push(item.data); });
        NSMobile.stores.prospectContacts.each(function (item) { contacts.push(item.data); });
        NSMobile.stores.allContacts.loadData(contacts, false);
        contactsLoaded = true;
    }

    lock = false;
}

var teamLoaded = false, customersLoaded = false, groupLoaded = false, aflLoaded = false, contactsLoaded = false, lock = false, prospectsLoaded = false;
var perfContactStore = NSMobile.stores.groupContactsPaginated;
var loadPerfContactsFresh = false;
var networkSorted = false;